package com.whu.UVAProtocol;

import com.whu.service.impl.PictureService;
import com.whu.service.impl.TrackInfoService;
import io.netty.bootstrap.ServerBootstrap;

import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description
 * @Author chengeng
 * @Date 2021/10/28 17:03
 **/
@Component
@Slf4j
public class UVAServer {
    private int port;
//    @Value("${pic.path}")
//    public String picPath;

    //管理所有的无人机信息和连接状态
    public static ConcurrentHashMap<Integer,UVAConnection> uvaConnections = new ConcurrentHashMap<>();
    //管理所有没有收到断联报文但是断开TCP连接的会话
    public static ConcurrentHashMap<Integer,UVAConnection> disconnections = new ConcurrentHashMap<>();
    //无人机连接会话过期时间 /分钟
    public static final long connectionMST = 1;

    public static final AttributeKey<Integer> channel_key = AttributeKey.valueOf("uva_id");

    //服务器到客户端，方向为1
    public static final byte DIRECTION = 0x01;
    public static final byte SERVER_ADDRESS = 0x00;


    public static PictureService pictureService;
    public static TrackInfoService trackInfoService;
    @Autowired
    public void setPictureService(PictureService pictureService,TrackInfoService trackInfoService) {
        UVAServer.pictureService = pictureService;
        UVAServer.trackInfoService = trackInfoService;
    }


    public void run() throws InterruptedException {
        log.info(this.port+"端口服务器启动中......");
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new UVAServerInitializer()); //自定义一个初始化类
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync().addListener((ChannelFutureListener) cf -> log.info("服务器关闭"));
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public UVAServer(int port) {
        this.port = port;
    }

    public UVAServer() {
    }

}
